package cn.hxzy.interceptor;

import cn.hxzy.util.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //UTF-8
        response.setCharacterEncoding("UTF-8");
        //响应json格式数据
        response.setContentType("application/json");

        String authorization = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(authorization)){
            DecodedJWT verify = null;
            try{
                verify= JWT.require(Algorithm.HMAC256(JWTUtil.KEY)).build().verify(authorization);
            }
            catch (SignatureVerificationException e){
                e.printStackTrace();
                response.getWriter().write(this.errorResponse("签名不一致:"+e.getMessage()));
                return false;
            }
            catch (TokenExpiredException e){
                e.printStackTrace();
                response.getWriter().write(this.errorResponse("令牌过期:"+e.getMessage()));
                return false;
            }
            catch (AlgorithmMismatchException e){
                e.printStackTrace();
                response.getWriter().write(this.errorResponse("签名算法不匹配:"+e.getMessage()));
                return false;
            }
            catch (InvalidClaimException e){
                e.printStackTrace();
                response.getWriter().write(this.errorResponse("payload不可用:"+e.getMessage()));
                return false;
            }
            Claim claim = verify.getClaim("userName");
            String userName = claim.asString();
            Long expire = redisTemplate.getExpire(userName);
            System.out.println(expire);
            if (expire>600) {
                String jwt = JWTUtil.createJwt(userName);
                redisTemplate.opsForValue().set(userName,jwt,1800L, TimeUnit.SECONDS);
            }
            request.setAttribute("claim",claim);
            return true;
        }else {
            response.getWriter().write(this.errorResponse("authorization为空"));
            return false;
        }

    }


    /**
     * 私有方法，返回json字符串格式的错误信息
     *
     * @param msg 错误信息内容
     * @return json字符串
     */
    private String errorResponse(String msg) {
        Map map = new HashMap(2){
            {
                put("code", -1);
                put("msg", msg);
            }
        };
        return JSON.toJSONString(map);
    }
}
